package org.fage.semples.dao;

import java.util.ArrayList;
import java.util.List;

import org.fage.semples.model.ExamUser;
import org.fage.semples.model.PagerModel;
import org.fage.semples.util.SystemContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class ExamUserHiberanteDAOImpI extends BaseHibernateDAO<ExamUser> implements ExamUserHiberanteDAO {

	@Autowired
	private ExamUserRoleHiberanteDAO examUserRoleHiberanteDAO;
	
	@SuppressWarnings("unchecked")
	public PagerModel<ExamUser> findAllByPage() {
		PagerModel<ExamUser> page = new PagerModel<ExamUser>();
		ArrayList<ExamUser> dates = new ArrayList<ExamUser> ();
		int offset = SystemContext.getOffset();
		int pageSize = SystemContext.getSize();
		//使用hibernate完成分页
		List<ExamUser> tempDates = this.getSession().createQuery(" from ExamUser ").setFirstResult(offset).setMaxResults(pageSize).list();
		for(ExamUser examUser : tempDates){
			dates.add(examUser);
		}
		page.setDates(dates);
		page.setOffset(offset);
		page.setPageSize(pageSize);
		
		//获取总记录数
		long totalSize = (long)this.getSession().createQuery("select count(*) from ExamUser").uniqueResult();
		page.setTotalSize(totalSize);
		
		return page;
	}
	
	@Override
	public List<ExamUser> findAllExamUsers() {
		return this.find("FROM ExamUser");
	}

	@Override
	public ExamUser getExamUserById(String userId) throws Exception{
		return this.get(userId);
		/*String sql = "select * from exam_user where user_id = :userId";
		return (ExamUser) createSqlQuery(sql).setString("userId", userId).uniqueResult();*/
	}

	@Override
	public void editExamUser(ExamUser examUser) throws Exception {
		this.update(examUser);
	}

	@Override
	public void createExamUser(ExamUser examUser) throws Exception {
		this.saveOrUpdate(examUser);
		String userId = examUser.getUserId();
		int roleId = Integer.parseInt(userId);
		examUserRoleHiberanteDAO.addExamRole(roleId);
		examUserRoleHiberanteDAO.addExamUserRole(roleId, userId);
	}
	
	@Override
	public void deleteExamUser(String userId) throws Exception {
		int roleId = Integer.parseInt(userId);
		examUserRoleHiberanteDAO.deleteExamRole(roleId);
		examUserRoleHiberanteDAO.deleteExamUserRole(roleId, userId);
		this.deleteByKey(userId);
	}

	@Override
	public void createExamUserList(List<ExamUser> examUserList) throws Exception {
		this.saveOrUpdate(examUserList);
	}


}
